import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../providers/anime_provider.dart';
import '../widgets/anime_banner.dart';
import '../../core/utils/chinese_title_mapper.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/mal_genres.dart';
import '../../domain/entities/anime.dart';
import 'ranking_page.dart';

/// 动漫列表页面
class AnimeListPage extends StatefulWidget {
  const AnimeListPage({super.key});

  @override
  State<AnimeListPage> createState() => _AnimeListPageState();
}

class _AnimeListPageState extends State<AnimeListPage> with TickerProviderStateMixin {
  late TabController _tabController;
  int _selectedTabIndex = 0;

  final List<Map<String, dynamic>> _tabs = [
    {'title': '推荐', 'icon': Icons.recommend},
    {'title': '分类', 'icon': Icons.category},
    {'title': '排行', 'icon': Icons.leaderboard},
    {'title': '专题', 'icon': Icons.topic},
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this);
    
    // 初始化时不需要主动加载数据，因为在HomePage中已经调用了initializeData()
    // initializeData()会优先加载缓存，然后后台刷新
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        backgroundColor: Theme.of(context).colorScheme.surface,
        body: RefreshIndicator(
          onRefresh: () async {
            final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
            await animeProvider.refreshAllData();
          },
          child: NestedScrollView(
            headerSliverBuilder: (context, innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  title: Text('AniQuest'),
                  actions: [
                    IconButton(
                      onPressed: () {
                        Navigator.pushNamed(context, '/search');
                      },
                      icon: const Icon(Icons.search),
                    ),
                  ],
                ),
                SliverToBoxAdapter(
                  child: Container(
                    height: 48,
                    child: TabBar(
                      controller: _tabController,
                      isScrollable: false,
                      indicatorColor: Theme.of(context).primaryColor,
                      indicatorWeight: 3,
                      labelColor: Theme.of(context).primaryColor,
                      unselectedLabelColor: Colors.grey[600],
                      labelStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                      ),
                      unselectedLabelStyle: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.normal,
                      ),
                      onTap: (index) {
                        setState(() {
                          _selectedTabIndex = index;
                        });
                      },
                      tabs: _tabs.map((tab) => Tab(
                        text: tab['title'],
                      )).toList(),
                    ),
                  ),
                ),
              ];
            },
            body: _buildTabContent(),
          ),
        ),
      ),
    );
  }

  Widget _buildTabContent() {
    switch (_selectedTabIndex) {
      case 0:
        return _buildRecommendTab();
      case 1:
        return _buildCategoryTab();
      case 2:
        return _buildRankingTab();
      case 3:
        return _buildTopicTab();
      default:
        return _buildRecommendTab();
    }
  }

  /// 根据屏幕宽度计算建议的初始卡片数量
  int _getRecommendedCardCount(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    
    if (screenWidth > 1200) {
      return 10; // 超大屏幕：加载更多
    } else if (screenWidth > 800) {
      return 8; // 平板：中等数量
    } else if (screenWidth > 600) {
      return 6; // 大手机：标准数量
    } else {
      return 6; // 小手机：保持6个以确保有足够的滑动内容
    }
  }

  // 推荐页面
  Widget _buildRecommendTab() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        final recommendedCount = _getRecommendedCardCount(context);
        
        return CustomScrollView(
          slivers: [
            // 轮播图区域 - 即将上线的动漫
            SliverToBoxAdapter(
              child: Container(
                margin: const EdgeInsets.only(top: 8),
                child: _buildBannerSection(provider),
              ),
            ),

            // 热门推荐模块
            _buildSectionTitle('热门推荐'),
            _buildHorizontalAnimeList(provider.trendingAnime.take(recommendedCount).toList()),

            // 最新更新模块
            _buildSectionTitle('最新更新'),
            _buildRecentEpisodesSection(provider),

            // 本季新番模块
            _buildSectionTitle('本季新番'),
            _buildSeasonalAnimeSection(provider),

            // 近期必看模块 - 响应式布局
            _buildSectionTitle('近期必看'),
            _buildResponsiveMustWatchSection(provider),

            // 即将完结模块
            _buildSectionTitle('即将完结'),
            _buildHorizontalAnimeList(
              _getEndingSoonAnime(provider).take(recommendedCount).toList(),
            ),

            // 热门更新模块
            _buildSectionTitle('热门更新'),
            _buildTrendingUpdateList(
              provider.trendingAnime.take(recommendedCount).toList(),
            ),

            // 经典回顾模块
            _buildSectionTitle('经典回顾'),
            _buildHorizontalAnimeList(provider.trendingAnime.skip(6).take(recommendedCount).toList()),

            const SliverToBoxAdapter(child: SizedBox(height: 20)),
          ],
        );
      },
    );
  }

  /// 构建轮播图区域
  Widget _buildBannerSection(AnimeProvider provider) {
    // 构建轮播图数据，优先选择热门和即将上线的动漫
    List<Anime> bannerList = [];
    
    // 添加即将上线的动漫
    if (provider.upcomingAnime.isNotEmpty) {
      bannerList.addAll(provider.upcomingAnime.take(3));
    }
    
    // 如果数据不足，添加热门动漫
    if (bannerList.length < 3 && provider.trendingAnime.isNotEmpty) {
      final needed = 3 - bannerList.length;
      final trendingToAdd = provider.trendingAnime
          .where((anime) => !bannerList.any((existing) => existing.id == anime.id))
          .take(needed)
          .toList();
      bannerList.addAll(trendingToAdd);
    }
    
    // 如果还是不足，添加本季新番
    if (bannerList.length < 3 && provider.seasonalAnime.isNotEmpty) {
      final needed = 3 - bannerList.length;
      final seasonalToAdd = provider.seasonalAnime
          .where((anime) => !bannerList.any((existing) => existing.id == anime.id))
          .take(needed)
          .toList();
      bannerList.addAll(seasonalToAdd);
    }
    
    // 调试信息
    print('轮播图数据构建情况:');
    print('- 即将上线数量: ${provider.upcomingAnime.length}');
    print('- 热门推荐数量: ${provider.trendingAnime.length}');
    print('- 本季新番数量: ${provider.seasonalAnime.length}');
    print('- 最终轮播数量: ${bannerList.length}');
    
    return AnimeBanner(
      animeList: bannerList,
      onTap: (anime) {
        Navigator.pushNamed(
          context,
          '/detail',
          arguments: {'id': anime.id},
        );
      },
    );
  }

  // 获取最新更新的动漫
  List<Anime> _getLatestUpdateAnime(AnimeProvider provider) {
    // 直接使用最新剧集数据
    final recentEpisodes = provider.recentEpisodes;
    
    // 调试信息
    print('最新更新数据获取情况:');
    print('- 原始数据数量: ${recentEpisodes.length}');
    print('- 加载状态: isLoading=${provider.isLoading}, hasError=${provider.hasError}');
    if (provider.hasError) {
      print('- 错误信息: ${provider.errorMessage}');
    }
    
    return recentEpisodes;
  }

  // 构建本季新番区域，包含错误处理
  Widget _buildSeasonalAnimeSection(AnimeProvider provider) {
    if (provider.isLoading && provider.seasonalAnime.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(
          height: 180, // 增加高度避免溢出
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min, // 最小化尺寸
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text(
                  '正在加载本季新番...',
                  style: TextStyle(color: Colors.grey),
                ),
          ],
            ),
          ),
        ),
    );
  }

    if (provider.hasError && provider.seasonalAnime.isEmpty) {
      return SliverToBoxAdapter(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          constraints: const BoxConstraints(minHeight: 180), // 使用最小高度约束
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min, // 最小化Column尺寸
                children: [
                  Icon(Icons.error_outline, size: 48, color: Colors.grey[400]),
                  const SizedBox(height: 8),
                  Text(
                    '本季新番加载失败',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    provider.errorMessage,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[500],
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                        onPressed: () async {
                          // 显示加载提示
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('正在重新获取数据...'),
                              duration: Duration(seconds: 2),
        ),
                          );
                          
                          // 重新获取数据
                          await provider.fetchSeasonalAnime(refresh: true);
                        },
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

    if (provider.seasonalAnime.isEmpty) {
    return SliverToBoxAdapter(
      child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          constraints: const BoxConstraints(minHeight: 180), // 使用最小高度约束
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min, // 最小化Column尺寸
          children: [
                  Icon(Icons.tv_off, size: 48, color: Colors.grey[400]),
                  const SizedBox(height: 8),
            Text(
                    '暂无本季新番数据',
                    style: TextStyle(
                      fontSize: 16,
                fontWeight: FontWeight.bold,
                      color: Colors.grey[600],
              ),
            ),
                  const SizedBox(height: 4),
                  Text(
                    '请稍后再试',
                style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[500],
                    ),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                        onPressed: () async {
                          // 显示加载提示
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('正在重新获取数据...'),
                              duration: Duration(seconds: 2),
              ),
                          );
                          
                          // 重新获取数据
                          await provider.fetchSeasonalAnime(refresh: true);
                        },
                        child: const Text('重试'),
                      ),
                    ],
            ),
          ],
              ),
            ),
        ),
      ),
    );
  }

    return _buildHorizontalAnimeList(
      provider.seasonalAnime.take(8).toList(),
        );
  }

  // 构建响应式近期必看区域
  Widget _buildResponsiveMustWatchSection(AnimeProvider provider) {
    final mustWatchList = _getRecentMustWatchAnime(provider).take(4).toList();
    
    if (mustWatchList.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(
          height: 120,
          child: Center(
            child: Text(
              '暂无数据',
              style: TextStyle(color: Colors.grey),
            ),
          ),
        ),
      );
    }

    return SliverToBoxAdapter(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final screenWidth = constraints.maxWidth;
          
          // 根据屏幕宽度决定布局
          if (screenWidth > 1000) {
            // 超大屏幕：一行显示2个卡片
            return _buildMustWatchGrid(mustWatchList, 2);
          } else if (screenWidth > 600) {
            // 平板：一行显示2个卡片，但使用水平滚动
            return _buildMustWatchHorizontalList(mustWatchList, screenWidth * 0.45);
          } else {
            // 手机：使用水平滚动，一个卡片占据大部分宽度
            return _buildMustWatchHorizontalList(mustWatchList, screenWidth * 0.85);
          }
        },
      ),
    );
  }

  // 构建必看动漫网格布局（大屏幕）
  Widget _buildMustWatchGrid(List<dynamic> animeList, int crossAxisCount) {
          return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: crossAxisCount,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
          childAspectRatio: 2.2, // 卡片宽高比
        ),
        itemCount: animeList.length,
        itemBuilder: (context, index) {
          return _buildMustWatchCard(animeList[index]);
        },
      ),
    );
  }

  // 构建必看动漫水平滚动列表（中小屏幕）
  Widget _buildMustWatchHorizontalList(List<dynamic> animeList, double cardWidth) {
    return Container(
      height: 200,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: animeList.length,
              itemBuilder: (context, index) {
                final anime = animeList[index];
                return Container(
                  width: cardWidth,
            margin: const EdgeInsets.only(right: 16),
            child: _buildMustWatchCard(anime),
          );
        },
      ),
    );
  }

  // 获取近期必看动漫
  List<dynamic> _getRecentMustWatchAnime(AnimeProvider provider) {
    List<dynamic> mustWatchList = [];
    
    // 选择高分动漫
    if (provider.trendingAnime.isNotEmpty) {
      final highRatedAnime = provider.trendingAnime.where((anime) {
        return anime.score >= 8.0;
      }).toList();
      mustWatchList.addAll(highRatedAnime.take(3));
    }
    
    // 补充当季动漫
    if (mustWatchList.length < 4 && provider.seasonalAnime.isNotEmpty) {
      final needed = 4 - mustWatchList.length;
      mustWatchList.addAll(provider.seasonalAnime.take(needed));
    }

    return mustWatchList;
  }

  // 获取即将完结的动漫
  List<dynamic> _getEndingSoonAnime(AnimeProvider provider) {
    List<dynamic> endingList = [];
    
    // 从当季动漫中筛选状态为"播放中"的
    if (provider.seasonalAnime.isNotEmpty) {
      final airingAnime = provider.seasonalAnime.where((anime) {
        return anime.status == 'Currently Airing';
      }).toList();
      endingList.addAll(airingAnime.take(4));
    }
    
    // 如果不够，补充热门动漫
    if (endingList.length < 6 && provider.trendingAnime.isNotEmpty) {
      final needed = 6 - endingList.length;
      endingList.addAll(provider.trendingAnime.take(needed));
    }
    
    return endingList;
  }

  // 构建最新更新区域，包含错误处理
  Widget _buildRecentEpisodesSection(AnimeProvider provider) {
    final latestAnime = _getLatestUpdateAnime(provider);
    
    if (provider.isLoading && latestAnime.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(
          height: 180,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16),
                Text(
                  '正在加载最新更新...',
                  style: TextStyle(color: Colors.grey),
                ),
              ],
            ),
          ),
        ),
      );
    }

    if (provider.hasError && latestAnime.isEmpty) {
      return SliverToBoxAdapter(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          constraints: const BoxConstraints(minHeight: 180),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.error_outline, size: 48, color: Colors.grey[400]),
                  const SizedBox(height: 8),
                  Text(
                    '最新更新加载失败',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    provider.errorMessage,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[500],
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                        onPressed: () async {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('正在重新获取最新更新数据...'),
                              duration: Duration(seconds: 2),
                            ),
                          );
                          await provider.fetchRecentEpisodes();
                        },
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

    if (latestAnime.isEmpty) {
      return SliverToBoxAdapter(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          constraints: const BoxConstraints(minHeight: 180),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.tv_off, size: 48, color: Colors.grey[400]),
                  const SizedBox(height: 8),
                  Text(
                    '暂无最新更新数据',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '可能被内容过滤器过滤或API暂无数据',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[500],
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                        onPressed: () async {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('正在重新获取最新更新数据...'),
                              duration: Duration(seconds: 2),
                            ),
                          );
                          await provider.fetchRecentEpisodes();
                        },
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

    final recommendedCount = _getRecommendedCardCount(context);
    return _buildHorizontalAnimeList(latestAnime.take(recommendedCount).toList());
  }

  // 构建更新页面的垂直列表（卡片样式）
  Widget _buildUpdateVerticalList(List<dynamic> animeList) {
    if (animeList.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(
          height: 120,
          child: Center(
            child: Text(
              '暂无数据',
              style: TextStyle(color: Colors.grey),
            ),
          ),
        ),
      );
    }

    return SliverToBoxAdapter(
      child: Container(
        height: 200,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: animeList.length,
          itemBuilder: (context, index) {
          final anime = animeList[index];
            return Container(
              width: 280,
              margin: const EdgeInsets.only(right: 16),
              child: _buildMustWatchCard(anime),
            );
        },
        ),
      ),
    );
  }

  // 构建必看动漫卡片
  Widget _buildMustWatchCard(dynamic anime) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title ?? '未知标题',
      titleJapanese: anime.titleJapanese ?? '',
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms ?? [],
    );
    final chineseGenres = ChineseTitleMapper.getChineseGenres(anime.genres ?? []);

    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
      onTap: () {
        Navigator.pushNamed(
          context,
          '/detail',
          arguments: {'id': anime.id},
        );
      },
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.white,
                Colors.grey.shade50,
              ],
            ),
          ),
          child: Row(
        children: [
              // 左侧封面
          Container(
                width: 100,
                height: 150,
                margin: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    imageUrl: anime.imageUrl ?? '',
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      color: Colors.grey[200],
                      child: const Center(child: CircularProgressIndicator()),
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: Colors.grey[200],
                      child: const Icon(Icons.image_not_supported),
                    ),
            ),
          ),
              ),
              
              // 右侧信息
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
              chineseTitle,
              style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
                      const SizedBox(height: 8),
                      
                      if (chineseGenres.isNotEmpty)
                        Wrap(
                          spacing: 4,
                          children: chineseGenres.take(3).map((genre) =>
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: Colors.blue.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Text(
                                genre,
              style: TextStyle(
                                  fontSize: 10,
                                  color: Colors.blue[700],
                                ),
                              ),
                            ),
                          ).toList(),
                        ),
                      
                      const SizedBox(height: 8),
                      
                      if ((anime.synopsis ?? '').isNotEmpty)
                        Expanded(
                          child: Text(
                            anime.synopsis,
                            style: TextStyle(
                              fontSize: 12,
                color: Colors.grey[600],
                              height: 1.3,
                            ),
                            maxLines: 4,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      
                      const SizedBox(height: 8),
                      
                      Row(
                        children: [
                          if ((anime.score ?? 0) > 0) ...[
                            Icon(Icons.star, color: Colors.amber, size: 16),
                            const SizedBox(width: 4),
                            Text(
                              anime.score.toStringAsFixed(1),
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.amber,
              ),
            ),
          ],
                          const Spacer(),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: Theme.of(context).primaryColor.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              '必看',
                              style: TextStyle(
                                fontSize: 10,
                                color: Theme.of(context).primaryColor,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建热门更新列表
  Widget _buildTrendingUpdateList(List<dynamic> animeList) {
    if (animeList.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(height: 120, child: Center(child: Text('暂无数据'))),
      );
    }

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          final anime = animeList[index];
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
            child: _buildTrendingUpdateCard(anime, index + 1),
          );
        },
        childCount: animeList.length,
      ),
    );
  }

  // 构建热门更新卡片
  Widget _buildTrendingUpdateCard(dynamic anime, int rank) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title ?? '未知标题',
      titleJapanese: anime.titleJapanese ?? '',
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms ?? [],
    );

    return Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        child: InkWell(
          borderRadius: BorderRadius.circular(8),
          onTap: () {
            Navigator.pushNamed(
              context,
              '/detail',
              arguments: {'id': anime.id},
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Row(
              children: [
              // 排名
              Container(
                width: 30,
                height: 30,
                decoration: BoxDecoration(
                  color: rank <= 3 ? Colors.red : Theme.of(context).primaryColor,
                  shape: BoxShape.circle,
                ),
                child: Center(
                  child: Text(
                    '$rank',
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                            ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
              
              // 封面
              Container(
                width: 50,
                height: 70,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: CachedNetworkImage(
                    imageUrl: anime.imageUrl ?? '',
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      color: Colors.grey[200],
                    ),
                    errorWidget: (context, url, error) => Container(
                      color: Colors.grey[200],
                      child: const Icon(Icons.image, size: 20),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              
              // 信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        chineseTitle,
                        style: const TextStyle(
                        fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        if ((anime.score ?? 0) > 0) ...[
                          Icon(Icons.star, color: Colors.amber, size: 14),
                          const SizedBox(width: 2),
                        Text(
                            anime.score.toStringAsFixed(1),
                            style: const TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(width: 12),
                        ],
                        if ((anime.episodes ?? 0) > 0)
                          Text(
                            '${anime.episodes}话',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              
              // 热度指示器
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.red.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.local_fire_department, size: 12, color: Colors.red),
                    const SizedBox(width: 2),
                    Text(
                      '热',
                      style: TextStyle(
                        fontSize: 10,
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 分类页面
  Widget _buildCategoryTab() {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: _buildCategoryGrid(),
        ),
      ],
    );
  }

  // 排行页面
  Widget _buildRankingTab() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return CustomScrollView(
          slivers: [
            // 排行榜标题卡片
            SliverToBoxAdapter(
              child: Container(
                margin: const EdgeInsets.all(16),
                child: Card(
                  elevation: 4,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          Theme.of(context).primaryColor,
                          Theme.of(context).primaryColor.withValues(alpha: 0.8),
                        ],
                      ),
                    ),
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.leaderboard,
                              color: Colors.white,
                              size: 28,
                            ),
                            const SizedBox(width: 12),
                            Text(
                              '动漫排行榜',
                              style: TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '发现最受欢迎的动漫作品',
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.white.withValues(alpha: 0.9),
                          ),
                        ),
                        const SizedBox(height: 16),
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton.icon(
                            onPressed: () {
                              // 使用平滑的页面跳转动画
                              Navigator.of(context).push(
                                PageRouteBuilder(
                                  pageBuilder: (context, animation, secondaryAnimation) {
                                    return FadeTransition(
                                      opacity: animation,
                                      child: SlideTransition(
                                        position: Tween<Offset>(
                                          begin: const Offset(0.1, 0),
                                          end: Offset.zero,
                                        ).animate(CurvedAnimation(
                                          parent: animation,
                                          curve: Curves.easeOutCubic,
                                        )),
                                        child: const RankingPage(),
                                      ),
                                    );
                                  },
                                  transitionDuration: const Duration(milliseconds: 300),
                                  reverseTransitionDuration: const Duration(milliseconds: 250),
                                ),
                              );
                            },
                            icon: Icon(Icons.arrow_forward, color: Theme.of(context).primaryColor),
                            label: Text(
                              '查看完整排行榜',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                                color: Theme.of(context).primaryColor,
                              ),
                            ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.white,
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                            ),
                              ),
                            ),
                          ],
                        ),
                  ),
                ),
              ),
            ),

            // 排行榜预览部分
            _buildRankingPreviewSection(provider),
          ],
        );
      },
    );
  }

  /// 构建排行榜预览部分
  Widget _buildRankingPreviewSection(AnimeProvider provider) {
    // 排行榜类型配置
    final List<Map<String, dynamic>> rankingTypes = [
      {
        'title': '评分排行',
        'subtitle': '最高评分动漫',
        'icon': Icons.star,
        'color': Colors.amber,
        'data': provider.rankingByScore,
      },
      {
        'title': '人气排行',
        'subtitle': '最受欢迎动漫',
        'icon': Icons.trending_up,
        'color': Colors.orange,
        'data': provider.rankingByPopularity,
      },
      {
        'title': '当前播放',
        'subtitle': '正在播放动漫',
        'icon': Icons.play_circle,
        'color': Colors.blue,
        'data': provider.rankingByMembers,
      },
      {
        'title': '喜爱排行',
        'subtitle': '最受喜爱动漫',
        'icon': Icons.favorite,
        'color': Colors.red,
        'data': provider.rankingByFavorites,
      },
    ];

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          final rankingType = rankingTypes[index];
          return _buildRankingPreviewCard(rankingType, provider);
        },
        childCount: rankingTypes.length,
      ),
    );
  }

  /// 构建单个排行榜预览卡片
  Widget _buildRankingPreviewCard(Map<String, dynamic> rankingType, AnimeProvider provider) {
    final List<dynamic> animeList = rankingType['data'] as List<dynamic>;
    final Color typeColor = rankingType['color'] as Color;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 排行榜类型标题
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: typeColor.withValues(alpha: 0.1),
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    rankingType['icon'] as IconData,
                    color: typeColor,
                    size: 24,
                  ),
                  const SizedBox(width: 12),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        rankingType['title'] as String,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: typeColor,
                        ),
                      ),
                      Text(
                        rankingType['subtitle'] as String,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                  ),
                ),
              ],
            ),
                  const Spacer(),
                  TextButton.icon(
                    onPressed: () {
                      Navigator.of(context).push(
                        PageRouteBuilder(
                          pageBuilder: (context, animation, secondaryAnimation) {
                            return FadeTransition(
                              opacity: animation,
                              child: SlideTransition(
                                position: Tween<Offset>(
                                  begin: const Offset(0.1, 0),
                                  end: Offset.zero,
                                ).animate(CurvedAnimation(
                                  parent: animation,
                                  curve: Curves.easeOutCubic,
                                )),
                                child: const RankingPage(),
                              ),
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                          reverseTransitionDuration: const Duration(milliseconds: 250),
                        ),
                      );
                    },
                    icon: Icon(Icons.arrow_forward_ios, size: 16, color: typeColor),
                    label: Text(
                      '更多',
                      style: TextStyle(color: typeColor, fontWeight: FontWeight.w600),
                    ),
                  ),
                ],
              ),
            ),

            // 排行榜预览列表 (显示前3名)
            if (provider.isLoading && animeList.isEmpty)
              Container(
                padding: const EdgeInsets.all(40),
                child: Center(
                  child: Column(
                    children: [
                      SizedBox(
                        width: 24,
                        height: 24,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(typeColor),
                        ),
                      ),
                      const SizedBox(height: 12),
                      Text(
                        '加载中...',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else if (animeList.isEmpty)
              Container(
                padding: const EdgeInsets.all(40),
                child: Center(
                  child: Column(
                    children: [
                      Icon(
                        Icons.inbox_outlined,
                        size: 48,
                        color: Colors.grey[400],
                      ),
                      const SizedBox(height: 12),
                      Text(
                        '暂无数据',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
              )
            else
              ...animeList.take(3).map((anime) {
                final rank = animeList.indexOf(anime) + 1;
                return _buildRankingPreviewItem(anime, rank, typeColor);
              }).toList(),
          ],
        ),
      ),
    );
  }

  /// 构建排行榜预览项目
  Widget _buildRankingPreviewItem(dynamic anime, int rank, Color rankColor) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title ?? '未知标题',
      titleJapanese: anime.titleJapanese ?? '',
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms ?? [],
    );

    return InkWell(
          onTap: () {
            Navigator.pushNamed(
              context,
              '/detail',
              arguments: {'id': anime.id},
            );
          },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              color: Colors.grey.shade200,
              width: 0.5,
            ),
          ),
        ),
            child: Row(
              children: [
            // 排名
                Container(
              width: 32,
              height: 32,
                  decoration: BoxDecoration(
                color: rank <= 3 
                    ? (rank == 1 ? Colors.amber : rank == 2 ? Colors.grey[400]! : Colors.brown[300]!)
                    : rankColor,
                borderRadius: BorderRadius.circular(16),
                  ),
                  child: Center(
                    child: Text(
                      '$rank',
                  style: const TextStyle(
                    color: Colors.white,
                        fontWeight: FontWeight.bold,
                    fontSize: 14,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

            // 封面
                ClipRRect(
              borderRadius: BorderRadius.circular(6),
                    child: SizedBox(
                width: 45,
                height: 60,
                child: (anime.imageUrl?.isNotEmpty ?? false)
                    ? CachedNetworkImage(
                        imageUrl: anime.imageUrl!,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Container(
                                  color: Colors.grey[300],
                          child: const Icon(Icons.image, size: 20, color: Colors.grey),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: Colors.grey[300],
                          child: const Icon(Icons.image_not_supported, size: 20, color: Colors.grey),
                        ),
                            )
                          : Container(
                              color: Colors.grey[300],
                        child: const Icon(Icons.image, size: 20, color: Colors.grey),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

            // 动漫信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        chineseTitle,
                        style: const TextStyle(
                      fontSize: 15,
                          fontWeight: FontWeight.w600,
                      color: Color(0xFF2C3E50),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                  if (anime.score != null && anime.score > 0)
                        Row(
                          children: [
                            Icon(Icons.star, color: Colors.amber, size: 14),
                            const SizedBox(width: 4),
                            Text(
                          '${anime.score.toStringAsFixed(1)}',
                              style: TextStyle(
                            fontSize: 13,
                            color: Colors.grey[700],
                            fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                    ],
                  ),
                ),

            // 前往图标
            Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colors.grey[400],
            ),
          ],
        ),
      ),
    );
  }

  // 分类网格
  Widget _buildCategoryGrid() {
    final categories = [
      {
        'icon': Icons.local_fire_department,
        'label': '热门',
        'color': Colors.orange,
        'type': 'filter',
        'value': 'bypopularity',
      },
      {
        'icon': Icons.fiber_new,
        'label': '新番',
        'color': Colors.green,
        'type': 'status',
        'value': 'currently airing',
      },
      {
        'icon': Icons.check_circle,
        'label': '完结',
        'color': Colors.blue,
        'type': 'status',
        'value': 'finished airing',
      },
      {
        'icon': Icons.movie,
        'label': '电影',
        'color': Colors.purple,
        'type': 'type',
        'value': 'movie',
      },
      {
        'icon': Icons.play_arrow,
        'label': 'OVA',
        'color': Colors.cyan,
        'type': 'type',
        'value': 'ova',
      },
      {
        'icon': Icons.video_library,
        'label': '特别篇',
        'color': Colors.red,
        'type': 'type',
        'value': 'special',
      },
      {
        'icon': Icons.favorite,
        'label': '恋爱',
        'color': Colors.pink,
        'type': 'genre',
        'value': 22, // Romance
      },
      {
        'icon': Icons.sports_martial_arts,
        'label': '动作',
        'color': Colors.deepOrange,
        'type': 'genre',
        'value': 1, // Action
      },
      {
        'icon': Icons.school,
        'label': '校园',
        'color': Colors.lightBlue,
        'type': 'genre',
        'value': 23, // School
      },
      {
        'icon': Icons.psychology,
        'label': '悬疑',
        'color': Colors.indigo,
        'type': 'genre',
        'value': 7, // Mystery
      },
      {
        'icon': Icons.self_improvement,
        'label': '日常',
        'color': Colors.pinkAccent,
        'type': 'genre',
        'value': 36, // Slice of Life
      },
      {
        'icon': Icons.sports_esports,
        'label': '游戏',
        'color': Colors.teal,
        'type': 'genre',
        'value': 11, // Game
      },
      {
        'icon': Icons.emoji_emotions,
        'label': '喜剧',
        'color': Colors.amber,
        'type': 'genre',
        'value': 4, // Comedy
      },
      {
        'icon': Icons.auto_fix_high,
        'label': '奇幻',
        'color': Colors.deepPurple,
        'type': 'genre',
        'value': 10, // Fantasy
      },
      {
        'icon': Icons.rocket_launch,
        'label': '科幻',
        'color': Colors.blueGrey,
        'type': 'genre',
        'value': 24, // Sci-Fi
      },
      {
        'icon': Icons.explore,
        'label': '冒险',
        'color': Colors.brown,
        'type': 'genre',
        'value': 2, // Adventure
      },
      {
        'icon': Icons.fitness_center,
        'label': '运动',
        'color': Colors.green[700]!,
        'type': 'genre',
        'value': 30, // Sports
      },
      {
        'icon': Icons.music_note,
        'label': '音乐',
        'color': Colors.purple[300]!,
        'type': 'genre',
        'value': 19, // Music
      },
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      child: LayoutBuilder(
        builder: (context, constraints) {
          // 根据屏幕宽度计算列数和高宽比
          final screenWidth = constraints.maxWidth;
          int crossAxisCount;
          double childAspectRatio;
          
          if (screenWidth > 600) {
            // 平板或大屏幕
            crossAxisCount = 6;
            childAspectRatio = 1.2;
          } else if (screenWidth > 360) {
            // 普通手机
            crossAxisCount = 4;
            childAspectRatio = 1.0;
          } else {
            // 小屏手机
            crossAxisCount = 3;
            childAspectRatio = 0.9;
          }
          
          return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: crossAxisCount,
          crossAxisSpacing: 12,
              mainAxisSpacing: 16,
              childAspectRatio: childAspectRatio,
        ),
        itemCount: categories.length,
        itemBuilder: (context, index) {
          final category = categories[index];
          return _buildCategoryCard(category);
            },
          );
        },
      ),
    );
  }

  Widget _buildCategoryCard(Map<String, dynamic> category) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            Navigator.pushNamed(
              context,
              RouteConstants.categoryDetail,
              arguments: {
                'categoryName': category['label'],
                'categoryType': category['type'],
                'categoryValue': category['value'],
                'categoryIcon': category['icon'],
                'categoryColor': category['color'],
              },
            );
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                category['icon'] as IconData,
                color: category['color'] as Color,
                  size: 28,
              ),
                const SizedBox(height: 6),
                Flexible(
                  child: Text(
                category['label'] as String,
                style: TextStyle(
                      fontSize: 11,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
                textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
              ),
            ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildError(String message, VoidCallback onRetry) {
    return Container(
      margin: const EdgeInsets.all(16),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 16),
              Text(
                '加载失败',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 8),
              Text(
                message,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[500],
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: onRetry,
                icon: const Icon(Icons.refresh),
                label: const Text('重试'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'currently airing':
        return Colors.green;
      case 'finished airing':
        return Colors.blue;
      case 'not yet aired':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  String _getStatusText(String status) {
    switch (status.toLowerCase()) {
      case 'currently airing':
        return '连载中';
      case 'finished airing':
        return '已完结';
      case 'not yet aired':
        return '未播出';
      default:
        return status;
    }
  }

  // 专题页面
  Widget _buildTopicTab() {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: _buildTopicGrid(),
        ),
      ],
    );
  }

  // 专题网格
  Widget _buildTopicGrid() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        final topics = _getTopicsWithImages(provider);

    return Container(
      padding: const EdgeInsets.all(16),
          child: LayoutBuilder(
            builder: (context, constraints) {
              // 根据屏幕宽度调整布局
              final screenWidth = constraints.maxWidth;
              int crossAxisCount;
              double childAspectRatio;
              
              if (screenWidth > 600) {
                // 平板或大屏幕：3列
                crossAxisCount = 3;
                childAspectRatio = 1.8;
              } else if (screenWidth > 360) {
                // 普通手机：2列，调整宽高比
                crossAxisCount = 2;
                childAspectRatio = 1.6;
              } else {
                // 小屏手机：2列，更窄的宽高比
                crossAxisCount = 2;
                childAspectRatio = 1.4;
              }
              
              return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: crossAxisCount,
          crossAxisSpacing: 12,
                  mainAxisSpacing: 16,
                  childAspectRatio: childAspectRatio,
        ),
        itemCount: topics.length,
        itemBuilder: (context, index) {
          final topic = topics[index];
          return _buildTopicCard(topic);
        },
              );
            },
      ),
    );
      },
    );
  }

  // 获取带有背景图片的专题数据
  List<Map<String, dynamic>> _getTopicsWithImages(AnimeProvider provider) {
    final topics = [
      {
        'title': '科幻未来',
        'subtitle': '未来科技',
        'color': Colors.blueGrey,
        'categoryType': 'genre',
        'categoryValue': 24, // Sci-Fi genre
      },
      {
        'title': '异世界冒险',
        'subtitle': '穿越奇幻',
        'color': Colors.purple,
        'categoryType': 'genre',
        'categoryValue': 2, // Adventure genre
      },
      {
        'title': '搞笑喜剧',
        'subtitle': '轻松愉快',
        'color': Colors.amber,
        'categoryType': 'genre',
        'categoryValue': 4, // Comedy genre
      },
      {
        'title': '剧情佳作',
        'subtitle': '深度故事',
        'color': Colors.teal,
        'categoryType': 'genre',
        'categoryValue': 8, // Drama genre
      },
      {
        'title': '校园恋爱',
        'subtitle': '青春回忆',
        'color': Colors.pink,
        'categoryType': 'genre',
        'categoryValue': 22, // Romance genre
      },
      {
        'title': '悬疑推理',
        'subtitle': '烧脑佳作',
        'color': Colors.indigo,
        'categoryType': 'genre',
        'categoryValue': 7, // Mystery genre
      },
    ];

    // 准备高质量的备选图片列表
    final fallbackImages = _getHighQualityFallbackImages(provider);
    
    // 用于跟踪已使用的动漫ID，确保不重复
    final usedAnimeIds = <int>{};
    final usedImageUrls = <String>{}; // 同时跟踪已使用的图片URL
    
    // 为每个专题获取对应分类的第一张图片，确保不重复
    return topics.asMap().entries.map((entry) {
      final index = entry.key;
      final topic = entry.value;
      
      String? backgroundImage = _getTopicBackgroundImage(
        provider,
        topic['categoryType'] as String,
        topic['categoryValue'] as int,
        usedAnimeIds, // 传入已使用的动漫ID集合
        usedImageUrls, // 传入已使用的图片URL集合
      );
      
      // 如果没有找到匹配的图片，从备选图片中选择未使用的
      if (backgroundImage == null || backgroundImage.isEmpty) {
        for (final fallbackImage in fallbackImages) {
          if (!usedImageUrls.contains(fallbackImage)) {
            backgroundImage = fallbackImage;
            usedImageUrls.add(fallbackImage);
            print('专题 ${topic['title']} 使用备选图片: $backgroundImage');
            break;
          }
        }
      }
      
      return {
        ...topic,
        'image': backgroundImage ?? '',
      };
    }).toList();
  }

  // 获取高质量的备选图片列表
  List<String> _getHighQualityFallbackImages(AnimeProvider provider) {
    final allAnime = <dynamic>[
      ...provider.trendingAnime,
      ...provider.rankingByScore,
      ...provider.seasonalAnime,
      ...provider.rankingByPopularity,
    ];

    // 去重并按评分排序
    final uniqueAnime = <int, dynamic>{};
    for (final anime in allAnime) {
      if (anime.id != null && 
          anime.imageUrl != null && 
          anime.imageUrl.isNotEmpty &&
          anime.score != null &&
          anime.score > 7.0) { // 只选择高分动漫
        if (!uniqueAnime.containsKey(anime.id) || 
            (uniqueAnime[anime.id].score ?? 0.0) < anime.score) {
          uniqueAnime[anime.id] = anime;
        }
      }
    }

    final sortedAnime = uniqueAnime.values.toList();
    sortedAnime.sort((a, b) {
      final scoreA = a.score ?? 0.0;
      final scoreB = b.score ?? 0.0;
      return scoreB.compareTo(scoreA);
    });

    // 返回前20张高质量图片，确保有足够的备选
    return sortedAnime.take(20).map<String>((anime) => anime.imageUrl as String).toList();
  }

  // 根据分类获取第一张动漫图片作为专题背景
  String? _getTopicBackgroundImage(
    AnimeProvider provider,
    String categoryType,
    int categoryValue,
    Set<int> usedAnimeIds,
    Set<String> usedImageUrls,
  ) {
    // 合并所有可用的动漫数据
    final allAnime = <dynamic>[
      ...provider.trendingAnime,
      ...provider.seasonalAnime,
      ...provider.recentEpisodes,
      ...provider.rankingByScore,
      ...provider.rankingByPopularity,
    ];

    // 根据分类筛选动漫
    final filteredAnime = <dynamic>[];
    
    // 获取目标分类的所有可能名称
    final targetNames = _getAllGenreNames(categoryValue);
    
    for (final anime in allAnime) {
      if (anime.imageUrl == null || anime.imageUrl.isEmpty) continue;
      
      // 根据不同的分类类型进行筛选
      switch (categoryType) {
        case 'genre':
          if (anime.genres != null && anime.genres is List) {
            final animeGenres = anime.genres as List<String>;
            
            // 检查是否包含目标分类（支持多种名称变体）
            final hasTargetGenre = animeGenres.any((genre) {
              final lowerGenre = genre.toLowerCase();
              return targetNames.any((targetName) => 
                lowerGenre.contains(targetName.toLowerCase()) ||
                targetName.toLowerCase().contains(lowerGenre)
              );
            });
            
            if (hasTargetGenre) {
              filteredAnime.add(anime);
            }
          }
          break;
        case 'status':
          if (anime.status?.toLowerCase() == categoryValue.toString().toLowerCase()) {
            filteredAnime.add(anime);
          }
          break;
        case 'type':
          if (anime.type?.toLowerCase() == categoryValue.toString().toLowerCase()) {
            filteredAnime.add(anime);
          }
          break;
      }
    }

    // 去重，优先选择高分的动漫
    final uniqueAnime = <int, dynamic>{};
    for (final anime in filteredAnime) {
      if (anime.id != null && !uniqueAnime.containsKey(anime.id)) {
        uniqueAnime[anime.id] = anime;
      }
    }

    // 按评分排序，选择第一张高质量的图片
    final sortedAnime = uniqueAnime.values.toList();
    sortedAnime.sort((a, b) {
      final scoreA = a.score ?? 0.0;
      final scoreB = b.score ?? 0.0;
      return scoreB.compareTo(scoreA); // 降序排列
    });

    // 返回第一张有效图片
    for (final anime in sortedAnime) {
      if (anime.imageUrl != null && 
          anime.imageUrl.isNotEmpty && 
          !usedAnimeIds.contains(anime.id) &&
          !usedImageUrls.contains(anime.imageUrl)) {
        usedAnimeIds.add(anime.id);
        usedImageUrls.add(anime.imageUrl);
        return anime.imageUrl;
      }
    }

    return null;
  }

  // 获取分类的所有可能名称（包括英文、中文、变体）
  List<String> _getAllGenreNames(int genreId) {
    switch (genreId) {
      case 1: // Action
        return ['Action', '动作', 'Adventure', 'Shounen'];
      case 2: // Adventure
        return ['Adventure', '冒险', 'Fantasy', 'Isekai'];
      case 4: // Comedy
        return ['Comedy', '喜剧', 'Humor', 'Parody', 'Gag Humor'];
      case 7: // Mystery
        return ['Mystery', '悬疑', 'Thriller', 'Detective', 'Psychological'];
      case 10: // Fantasy
        return ['Fantasy', '奇幻', 'Magic', 'Supernatural'];
      case 11: // Game
        return ['Game', '游戏', 'Gaming'];
      case 18: // Mecha
        return ['Mecha', '机甲', 'Robot', 'Sci-Fi'];
      case 19: // Music
        return ['Music', '音乐', 'Musical', 'Idol', 'Idols'];
      case 22: // Romance
        return ['Romance', '恋爱', 'Love', 'Romantic', 'Shoujo'];
      case 23: // School
        return ['School', '校园', 'High School', 'University'];
      case 24: // Sci-Fi
        return ['Sci-Fi', '科幻', 'Science Fiction', 'Space', 'Future', 'Mecha'];
      case 30: // Sports
        return ['Sports', '运动', 'Sport', 'Competition', 'Athletic'];
      case 36: // Slice of Life
        return ['Slice of Life', '日常', 'Daily Life', 'Iyashikei', 'Healing'];
      case 13: // Historical
        return ['Historical', '历史', 'War', 'Battle', 'Historical Fiction'];
      case 8: // Drama
        return ['Drama', '剧情', 'Story', 'Depth', 'Emotional'];
      default:
        return ['Unknown'];
    }
  }

  Widget _buildTopicCard(Map<String, dynamic> topic) {
    final String imageUrl = topic['image'] as String;
    final Color fallbackColor = topic['color'] as Color;
    
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          fit: StackFit.expand,
          children: [
            // 背景图片或渐变
            imageUrl.isNotEmpty
                ? CachedNetworkImage(
                    imageUrl: imageUrl,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            fallbackColor.withValues(alpha: 0.8),
                            fallbackColor.withValues(alpha: 0.6),
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                      ),
                    ),
                    errorWidget: (context, url, error) => Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            fallbackColor.withValues(alpha: 0.8),
                            fallbackColor.withValues(alpha: 0.6),
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                      ),
                    ),
                  )
                : Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          fallbackColor.withValues(alpha: 0.8),
                          fallbackColor.withValues(alpha: 0.6),
                        ],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                    ),
                  ),
            
            // 深色遮罩层，确保文字可读性
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Colors.black.withValues(alpha: 0.3),
                    Colors.black.withValues(alpha: 0.6),
                  ],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                ),
              ),
            ),
            
            // 点击效果和内容
            Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            _handleTopicTap(topic['title'] as String);
          },
          child: Padding(
                  padding: const EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.end,
                    mainAxisSize: MainAxisSize.min,
              children: [
                      Flexible(
                        child: Text(
                  topic['title'],
                  style: const TextStyle(
                            fontSize: 15,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                            shadows: [
                              Shadow(
                                offset: Offset(0, 1),
                                blurRadius: 2,
                                color: Colors.black54,
                              ),
                            ],
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                  ),
                ),
                      const SizedBox(height: 2),
                      Flexible(
                        child: Text(
                  topic['subtitle'],
                          style: const TextStyle(
                            fontSize: 11,
                            color: Colors.white,
                            shadows: [
                              Shadow(
                                offset: Offset(0, 1),
                                blurRadius: 2,
                                color: Colors.black54,
                              ),
                            ],
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 处理专题卡片点击
  void _handleTopicTap(String topicTitle) {
    switch (topicTitle) {
      case '科幻未来':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '科幻动漫',
            'categoryType': 'genre',
            'categoryValue': 24, // Sci-Fi genre
                         'categoryIcon': Icons.rocket_launch,
            'categoryColor': Colors.blueGrey,
            'topicTitle': '科幻未来',
            'topicSubtitle': '未来科技的科幻世界',
          },
        );
        break;
      case '异世界冒险':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '异世界冒险',
            'categoryType': 'genre',
            'categoryValue': 2, // Adventure genre
            'categoryIcon': Icons.explore,
            'categoryColor': Colors.purple,
            'topicTitle': '异世界冒险',
            'topicSubtitle': '穿越到奇幻世界的冒险之旅',
          },
        );
        break;
      case '搞笑喜剧':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '搞笑喜剧',
            'categoryType': 'genre',
            'categoryValue': 4, // Comedy genre
            'categoryIcon': Icons.emoji_emotions,
            'categoryColor': Colors.amber,
            'topicTitle': '搞笑喜剧',
            'topicSubtitle': '轻松愉快的喜剧故事',
          },
        );
        break;

      case '校园恋爱':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '校园恋爱',
            'categoryType': 'genre',
            'categoryValue': 22, // Romance genre
            'categoryIcon': Icons.favorite,
            'categoryColor': Colors.pink,
            'topicTitle': '校园恋爱',
            'topicSubtitle': '青春甜蜜的校园时光',
          },
        );
        break;
      case '悬疑推理':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '悬疑推理',
            'categoryType': 'genre',
            'categoryValue': 7, // Mystery genre
            'categoryIcon': Icons.psychology,
            'categoryColor': Colors.indigo,
            'topicTitle': '悬疑推理',
            'topicSubtitle': '烧脑的推理与解谜',
          },
        );
        break;
      case '历史战争':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '历史战争',
            'categoryType': 'genre',
            'categoryValue': 13, // Historical genre
            'categoryIcon': Icons.military_tech,
            'categoryColor': Colors.brown,
            'topicTitle': '历史战争',
            'topicSubtitle': '战火纷飞的战争历史',
          },
        );
        break;
      case '剧情佳作':
        Navigator.pushNamed(
          context,
          RouteConstants.categoryDetail,
          arguments: {
            'categoryName': '剧情佳作',
            'categoryType': 'genre',
            'categoryValue': 8, // Drama genre
            'categoryIcon': Icons.book,
            'categoryColor': Colors.teal,
            'topicTitle': '剧情佳作',
            'topicSubtitle': '深度故事的剧情世界',
          },
        );
        break;
      default:
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('「$topicTitle」功能开发中，敬请期待！'),
            duration: const Duration(seconds: 2),
          ),
        );
    }
  }

  // 构建模块标题
  Widget _buildSectionTitle(String title) {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
        child: Row(
          children: [
            Container(
              width: 4,
              height: 20,
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            const SizedBox(width: 8),
            Text(
              title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Color(0xFF2C3E50),
              ),
            ),
            const Spacer(),
            TextButton(
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('${title}的更多内容开发中...')),
                );
              },
              child: Text(
                '更多 >',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 14,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建水平滚动的动漫列表
  Widget _buildHorizontalAnimeList(List<dynamic> animeList) {
    if (animeList.isEmpty) {
      return const SliverToBoxAdapter(
        child: SizedBox(height: 160, child: Center(child: Text('暂无数据'))),
      );
    }

    return SliverToBoxAdapter(
      child: LayoutBuilder(
        builder: (context, constraints) {
          final screenWidth = constraints.maxWidth;
          
          // 根据屏幕宽度自适应计算卡片大小和数量
          double cardWidth;
          int visibleCardCount;
          
          if (screenWidth > 1200) {
            // 超大屏幕：显示更多卡片
            cardWidth = 160;
            visibleCardCount = (screenWidth / (cardWidth + 12)).floor().clamp(3, 8);
          } else if (screenWidth > 800) {
            // 平板：中等数量卡片
            cardWidth = 140;
            visibleCardCount = (screenWidth / (cardWidth + 12)).floor().clamp(3, 6);
          } else if (screenWidth > 600) {
            // 大手机：较少卡片
            cardWidth = 120;
            visibleCardCount = (screenWidth / (cardWidth + 12)).floor().clamp(2, 5);
          } else {
            // 小手机：最少卡片
            cardWidth = 110;
            visibleCardCount = (screenWidth / (cardWidth + 12)).floor().clamp(2, 4);
          }
          
          final cardHeight = cardWidth * 4 / 3 + 60;

          return Container(
            height: cardHeight,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              itemCount: animeList.length,
              itemBuilder: (context, index) {
                final anime = animeList[index];
                return Container(
                  width: cardWidth,
                  margin: const EdgeInsets.only(right: 12),
                  child: _buildSmallAnimeCard(anime, cardWidth),
                );
              },
            ),
          );
        },
      ),
    );
  }

  // 小型动漫卡片（用于水平滚动）
  Widget _buildSmallAnimeCard(dynamic anime, double cardWidth) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
    );

    final imageHeight = cardWidth * 4 / 3;

    return InkWell(
      onTap: () {
        Navigator.pushNamed(
          context,
          '/detail',
          arguments: {'id': anime.id},
        );
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: cardWidth,
            height: imageHeight,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: anime.imageUrl != null && anime.imageUrl.isNotEmpty
                  ? CachedNetworkImage(
                      imageUrl: anime.imageUrl,
                      width: cardWidth,
                      height: imageHeight,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => Container(
                        width: cardWidth,
                        height: imageHeight,
                        color: Colors.grey[200],
                        child: const Center(
                          child: CircularProgressIndicator(strokeWidth: 2),
                        ),
                      ),
                      errorWidget: (context, url, error) {
                        print('图片加载失败: $url, 错误: $error');
                        return Container(
                          width: cardWidth,
                          height: imageHeight,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              colors: [
                                Colors.grey[300]!,
                                Colors.grey[400]!,
                              ],
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.image_not_supported,
                                size: cardWidth * 0.2,
                                color: Colors.grey[600],
                              ),
                              const SizedBox(height: 4),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 4),
                                child: Text(
                                  chineseTitle,
                                  style: TextStyle(
                                    fontSize: 8,
                                    color: Colors.grey[700],
                                    fontWeight: FontWeight.w500,
                                  ),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    )
                  : Container(
                      width: cardWidth,
                      height: imageHeight,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            Colors.grey[300]!,
                            Colors.grey[400]!,
                          ],
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.movie,
                            size: cardWidth * 0.2,
                            color: Colors.grey[600],
                          ),
                          const SizedBox(height: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 4),
                            child: Text(
                              chineseTitle,
                              style: TextStyle(
                                fontSize: 8,
                                color: Colors.grey[700],
                                fontWeight: FontWeight.w500,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ],
                      ),
                    ),
            ),
          ),
          const SizedBox(height: 8),
          SizedBox(
            width: cardWidth,
            child: Text(
              chineseTitle,
              style: const TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          if (anime.score != null && anime.score > 0) ...[
            const SizedBox(height: 4),
            Text(
              '${anime.score.toStringAsFixed(1)}分',
              style: TextStyle(
                fontSize: 9,
                color: Colors.grey[600],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildHomeTab() {
    return RefreshIndicator(
      onRefresh: () async {
        final animeProvider = Provider.of<AnimeProvider>(context, listen: false);
        await animeProvider.refreshAllData();
      },
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 缓存状态指示器
            _buildCacheStatusIndicator(),
            const SizedBox(height: 16),
            
            // 轮播图区域
            _buildCarouselSection(),
            const SizedBox(height: 24),
            
            // 热门推荐区域
            _buildPopularSection(),
            const SizedBox(height: 24),
            
            // 最新更新区域
            _buildLatestSection(),
            const SizedBox(height: 24),
            
            // 经典回顾区域
            _buildClassicSection(),
          ],
        ),
      ),
    );
  }

  /// 缓存状态指示器
  Widget _buildCacheStatusIndicator() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return FutureBuilder<Map<String, bool>>(
          future: provider.getCacheStatus(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const SizedBox.shrink();
            
            final cacheStatus = snapshot.data!;
            final cachedCount = cacheStatus.values.where((cached) => cached).length;
            final totalCount = cacheStatus.length;
            
            if (cachedCount == 0) return const SizedBox.shrink();
            
            return Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.secondaryContainer,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.cached,
                    size: 14,
                    color: Theme.of(context).colorScheme.onSecondaryContainer,
                  ),
                  const SizedBox(width: 4),
                  Text(
                    '缓存数据 $cachedCount/$totalCount',
                    style: TextStyle(
                      fontSize: 12,
                      color: Theme.of(context).colorScheme.onSecondaryContainer,
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildCarouselSection() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return AnimeBanner(
          animeList: provider.upcomingAnime.isNotEmpty 
              ? provider.upcomingAnime 
              : provider.seasonalAnime.take(3).toList(),
          onTap: (anime) {
            Navigator.pushNamed(
              context,
              '/detail',
              arguments: {'id': anime.id},
            );
          },
        );
      },
    );
  }

  Widget _buildPopularSection() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return _buildHorizontalAnimeList(provider.trendingAnime.take(6).toList());
      },
    );
  }

  Widget _buildLatestSection() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return _buildRecentEpisodesSection(provider);
      },
    );
  }

  Widget _buildClassicSection() {
    return Consumer<AnimeProvider>(
      builder: (context, provider, child) {
        return _buildHorizontalAnimeList(provider.trendingAnime.skip(6).take(6).toList());
      },
    );
  }
} 